package com.chang.bootplus.config.security;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chang.bootplus.entity.School;
import com.chang.bootplus.service.SchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {


	@Autowired
	SchoolService schoolService;

	@Override
	public UserDetails loadUserByUsername(String logName) throws UsernameNotFoundException {

	    School school = schoolService.getOne(new LambdaQueryWrapper<School>().eq(School::getNickName,logName));
		if (school == null) {
			throw new UsernameNotFoundException("账号或密码不正确");
		}

		return new AccountUser(school.getId(), school.getNickName(), school.getPassword(), getUserAuthority(school.getId()));
	}

	/**
	 * 获取用户权限信息（角色、菜单权限）
	 * @param userId
	 * @return list
	 */
	public List<GrantedAuthority> getUserAuthority(Long userId){

//		 角色(ROLE_admin)、菜单操作权限 sys:user:list
		String authority = schoolService.getUserAuthorityInfo(userId);  // ROLE_admin,ROLE_normal,sys:user:list,....

//		 将当前的 格式化字符串转化为权限集合
		return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
	}

}
